<?php
namespace app\api\controller;
use app\common\controller\IndexBaseController;
use app\web\model\AgentModel;
use think\Db;
/**
 * 商家
 */
class AgentController extends IndexBaseController {
	protected function _initialize() {
			 parent::_initialize();
	}
	/**
	 * 获取店铺信息
	 */
	 public function shopIndex(){
	 	
	 	$store_id = request() -> param('store_id');
		
		$storeInfo = db('mall_agent')->where('id',$store_id)->find();
		
		
		if ($storeInfo) {
			$grabGoods	= Db::name('mall_goods_grab')->where('agent_id',$store_id)->order('add_time DESC')->limit(3)->select();
			$scoreGoods = Db::name('mall_goods_score')->order('add_time DESC')->limit(3)->select();
			$discountGoods  = Db::name('mall_goods_discount')->order('add_time DESC')->limit(3)->select();
			$pintuanGoods  = Db::name('mall_goods_pintuan')->order('add_time DESC')->limit(3)->select();
			
			$storeIndex['storeInfo']= $storeInfo;
			$storeIndex['scoreGoods']= $scoreGoods;
			$storeIndex['discountGoods']= $discountGoods;
			$storeIndex['pintuanGoods']= $pintuanGoods;
			
			return $this -> toJson(200, '', $storeIndex);
		} else {
			return $this -> toJson(405, '数据不存在');
		}
	 }
	 /**
	  * @type 1限时 2限量3限购
	  */
	 public function getlimit(){
	 	 $type=input("type");
		 if($type==1){
		 	$where['limit1']=1;
		 }else if($type==2){
		 	$where['limit2']=1;
		 }else if($type==3){
		 	$where['is_zh']=1;
		 }
		 if(input("hyid")){
		 	$where['industry_id']=input("hyid");
		 }
		 $field="a.id,a.store_name,b.thumb,b.comment,b.goods_name,b.goods_names,b.start_time,b.end_time,b.people_num,b.id as gid,b.sale_price";
		 $list=db('mall_agent')->alias("a")->join("line_goods b","a.id=b.store_id","left")->where($where) ->field($field)->group("a.id")->select();
		 return json(['list'=>$list]);
	 }
	 /**
	  * 获取积分兑换商品
	  */
	 public function getScores(){
	 	 $type=input("type");
		 $where=' store_id =0 and bouns_flag= 1';
		 if(input("cate_id")){
		 	$where .=" and cate_id =".input("cate_id");
		 }
		 $sql ='select * from long_line_goods  where '.$where.' group by store_id ';
		 $list = Db::query($sql);
		 return json(['list'=>$list]);
	 }
	 //@type 1吃喝2玩乐3其他
	 public function getlist(){
	 	 $type=input("type");
		 //$where=' b.is_tj= 1';
		 if($type==1){
		 	$where=" a.industry_id in(1,2,3,4,6,7,8,10,12) ";
		 }elseif($type==2){
		 	$where="  a.industry_id in(5,9,10,11,12,13,14,15) ";
		 }else{
		 	$where="  a.industry_id in(5,17) ";
		 }
		 $where .=" and b.is_pk=1  ";
		 $latitude=input("latitude")?input("latitude"):'25.78226398';
		 $longitude=input("longitude")?input("longitude"):'113.03770447';
		 $sql ='select a.id,a.store_name,a.address,a.longitude,a.latitude,b.thumb,b.comment,b.sales,b.sale_price,b.goods_name,b.id as gid,'.
						' ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-a.latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(a.latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-a.longitude*PI()/180)/2),2)))*1000) AS juli'.
						' from long_mall_agent  as a LEFT JOIN long_line_goods as b ON a.id = b.store_id where '.$where.' group by a.id order by juli  ';
					
		 $list = Db::query($sql);
		 return json(['list'=>$list]);
	 }
	  /* POST
	 * 申请开店
	 */
	public function post() {
		if ($this -> request -> isPost()) {
			$data=input("post.");
			$data['add_time']=now_time();
			if($data['id']){
				$result=db('mall_agent')->where("id",$data['id'])->update($data);	
			}else{
				$result=db('mall_agent')->insert($data);	
			}
			if($result !== false){
				db("member")->where('id', input("u_id"))->update(['agent_type' => '2']);//修改用户为为已开店
				return $this->toJson(200, '保存成功');
			}else{
				return $this->toJson(406, '保存失败');
			}
		}
	}
	/**
	 * 商家后台首页
	 */
	public function store($uid){
		$store=db('mall_agent')->where('u_id',input("uid"))->find();
		$data['store']=$store;
		$data['cate']=$this->getCate();
		if(!$store){
			return $this->toJson(406, '店铺不存在',$data);
		}else{
			return $this->toJson(200, 'ok', $data);
		}
		
	}
	/**
	 * 获取商品分类
	 */
	public function getCate(){
		if (cache('cate')) {
			$cate = cache('cate');
		} else {
			$cate = db("mall_category")->where('level',2)->select();
			cache("cate",$cate);
		}
		return $cate;
	}
	
	
	
	//用户积分
	public function getUserScore (){
		$goodsType = request() -> param('goods_type');
		$goods_id = request() -> param('goods_id');
		$user_id = request() -> param('user_id');
		
		//获取商品信息
		$goodsTable = AgentController::getNumType($goodsType);
		$agent_id = Db::name($goodsTable)->where('id', $goods_id)->value('agent_id');
		
		$score = Db::name('mall_score')->where(['agent_id'=>$agent_id,'user_id' => $user_id])->sum('score');
		if($score){
			return $this->toJson(200, 'ok', $score);
		}else{
			return $this->toJson(405, '',0);
		}
		
	}
	
	//店铺前台首页
	public function store_indx(){
		$longitude = request() -> param('longitude');
		$latitude = request() -> param('latitude');
		$store_id = request() -> param('sid');
		
		//获取店铺信息
		$storeInfo = Db::name("mall_agent")->where('id', $store_id)->find();
		if($storeInfo){
			//获取云拼团商品
			$pintuans = Db::name("mall_goods_pintuan")->where('agent_id', $store_id)->order('add_time','desc')->limit(2)->select();
			//获取疯狂抢商品
			$grabs = Db::name("mall_goods_grab")->where('agent_id', $store_id)->order('add_time desc')->limit(3)->select();
			//获取赚积分商品
			$goods_score = Db::name("mall_goods_score")->where('agent_id', $store_id)->order('add_time desc')->limit(3)->select();
			//获取优惠购商品
			$discounts = Db::name("mall_goods_discount")->where('agent_id', $store_id)->order('add_time desc')->limit(3)->select();
			
			//获取连锁店信息
			$chainstore = Db::name("mall_chainstore")->where('agent_id', $store_id)->select();
			
			foreach($chainstore as $key=>$items){
				$distance = AgentController::GetDistance($longitude,$latitude,$items['longitude'],$items['latitude']);
				$chainstore[$key]['distance'] = $distance;
			}

			//获取商家联盟
			$unionstore = Db::name("mall_unionstore")->where('agent_id', $store_id)->select();
			
			$store_Info['storeInfo']  	= $storeInfo;
			$store_Info['pintuans']   	= $pintuans;
			$store_Info['grabs'] 	  	= $grabs;
			$store_Info['goods_score']  = $goods_score;
			$store_Info['discounts']  	= $discounts;
			$store_Info['chainstore'] 	= $chainstore;
			$store_Info['unionstore'] 	= $unionstore;
			
			return $this->toJson(200, 'ok', $store_Info);
		}else{
			return $this->toJson(405, '',"数据异常");
		}

	}
    //联盟前台首页
	public function unionstore_index(){
		$longitude = request() -> param('longitude');
		$latitude = request() -> param('latitude');
		$sid = request() -> param('sid');	
		$u_id = request() -> param('uid');				
		//获取商家联盟
		$unionstore = Db::name("mall_unionstore")->where('agent_id', $sid)->where('u_id',$u_id)->find();
		
		$where = ' order by juli asc ';
		$sql = 'select agent_id,agent_name,thumb,address,business_scope,longitude,latitude,template_id,ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli from long_mall_location'.$where.' limit 0,3';		
		$resultList=Db::query($sql);
		//$data = {"unionstore": $unionstore; "resultList": $resultList;}
		$list =array("unionstore"=>$unionstore,"resultList"=>$resultList);
		if($unionstore){
			return $this->toJson(200, 'ok', $list);
		}else{
			return $this->toJson(405, '',"数据异常");
		}

	}
	//获取附近商家
	public function get_distance_store(){
		$longitude = request() -> param('longitude');
		$latitude = request() -> param('latitude');
		//$next_page = request() -> param('next_page');
				
		$next_page =  intval(input('next_page')) ? intval(input('next_page')) : 1;
		//$sql ="select agent_id,agent_name,thumb,address,business_scope,longitude,latitude from long_mall_location where (acos(sin((".$latitude."*3.1415)/180) * sin((latitude*3.1415)/180) + cos((".$latitude."*3.1415)/180) * cos((latitude*3.1415)/180) * cos((".$longitude."*3.1415)/180 - (longitude*3.1415)/180))*6370.996)<=5";
		$where = ' order by juli asc ';
		$sql = 'select agent_id,agent_name,thumb,address,business_scope,longitude,latitude,ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli from long_mall_location'.$where.' limit '.(($next_page-1)*10).',10';
		
		$resultList=Db::query($sql);
		
		/*foreach($resultList as $key=>$items){
				$distance = AgentController::GetDistance($longitude,$latitude,$items['longitude'],$items['latitude']);
				$resultList[$key]['distance'] = $distance;
			}*/
		
		if($resultList){
			return $this->toJson(200, 'ok', $resultList);
		}else{
			return $this->toJson(405, '',"数据异常");
		}
		
		
	}
	

	//经纬度距离
	public function GetDistance($lat1, $lng1, $lat2, $lng2){
		 
	    $earthRadius = 6367000; 

	     $lat1 = ($lat1 * pi() ) / 180;
	     $lng1 = ($lng1 * pi() ) / 180;
	
	     $lat2 = ($lat2 * pi() ) / 180;
	     $lng2 = ($lng2 * pi() ) / 180;
	
	     $calcLongitude = $lng2 - $lng1;
	     $calcLatitude = $lat2 - $lat1;
	     $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
	     $calculatedDistance = $earthRadius * $stepTwo;
	
	     return round($calculatedDistance)/1000;
	}
	
	/**
	 * 获取连锁店列表
	 */
	function get_chainstores($page=1){
		//获取连锁店信息
		$chains_list = Db::name("mall_chainstore")->where('agent_id', input("sid"))->order('id desc')->paginate(4);
			
		if($chains_list){
			return $this->toJson(200, 'ok', $chains_list);
		}else{
			return $this->toJson(405, '',"数据异常");
		}
	}
	
	/**
	 * 添加店铺关注,收藏
	 */
	function solicitude(){
		$agent_id 		= request() -> param('sid');
		$uid 			= request() -> param('uid');
		$goods_id		= request() -> param('goods_id');
		$goods_lanmu	= request() -> param('goods_type');
		
		$collect['agent_id']		= $agent_id;
		$collect['uid'] 			= $uid;
		$collect['goods_id'] 		= $goods_id;
		$collect['goods_lanmu'] 	= $goods_lanmu;
		
		$result = db('mall_collect')->insert($collect);
		
		if($result){
			return $this->toJson(200, '关注成功！', '');
		}else{
			return $this->toJson(405, '',"数据异常");
		}
	}
	
	 /**
	 * 获取商品类型
	 */
	 public function getNumType($num){
	 	switch ($num)
		{
		case 2:
		  return "mall_goods_discount";
		  break;  
		case 4:
		   return "mall_goods_pintuan";
		  break;
		case 3:
		   return "mall_goods_score";
		  break;
		case 1:
		   return "mall_goods_grab";
		  break;
		default:
			return null;
		 break;
		}
	}
}
